<template>
  <div class="requestAdd">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button class="btn search" @click="getrealinvent"
        ><el-icon class="icon" color="#fff"> <Search /> </el-icon
        >查询</el-button
      >
      <el-button class="btn add" @click="handleRefresh"
        ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
        >重置</el-button
      >
      <el-button class="btn save" @click="handleExport()"
        ><el-icon class="icon" color="#fff"> <Download /> </el-icon
        >导出列表</el-button
      >
    </div>
    <!-- 筛选条件 -->
    <div class="search">
      <div class="search-item">
        <el-select
          v-model="params.type"
          placeholder="请选择文档类型"
          clearable
          class="search-input"
        >
          <!-- <el-option
            v-for="dict in contractList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          /> -->

          <el-option-group
            v-for="group in contractList"
            :key="group.label"
            :label="group.label"
          >
            <el-option
              v-for="item in group.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-option-group>
        </el-select>
      </div>
      <div class="search-item">
        <el-date-picker
          v-model="time"
          type="daterange"
          align="right"
          range-separator="至"
          start-placeholder="签订开始日期"
          end-placeholder="结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.contractCode"
          class="search-input"
          placeholder="请输入文件编号"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.projectCode"
          class="search-input"
          placeholder="请输入项目名称/项目编号"
        ></el-input>
      </div>
    </div>

    <div class="sum-box">
      <div class="sum-box-item">
        <span>
          销售总额：<span class="sum-text">{{ sumSaleAmount }}</span> 元
        </span>
      </div>
      <div class="sum-box-item">
        <span>
          采购总额：<span class="sum-text">{{ sumPurchaseAmount }}</span> 元
        </span>
      </div>
    </div>

    <div class="tabinfo">
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="projectContractList"
        border
        height="54vh"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="60"
          align="center"
        />

        <el-table-column
          label="文档类型"
          prop="typeName"
          :show-overflow-tooltip="true"
          min-width="100"
        />
        <el-table-column
          label="印章归属"
          prop="companySignet"
          :show-overflow-tooltip="true"
          min-width="120"
        />
        <!-- <el-table-column
          label="项目编号"
          prop="projectCode"
          :show-overflow-tooltip="true"
          min-width="180"
        >
          <template #default="{ row }">
            <span
              v-if="row.projectCode"
              @click="handleStock(row.projectId)"
              style="color: #409eff; cursor: pointer"
              >{{ row.projectCode }}</span
            >
            <span v-else>{{ "--" }}</span>
          </template>
        </el-table-column> -->

        <el-table-column
          label="项目编号"
          prop="projectCode"
          :show-overflow-tooltip="true"
          min-width="180"
        >
          <template #default="{ row }">
            <el-dropdown
              v-if="row.projectList"
              trigger="hover"
              @command="handleStock"
            >
              <span
                class="el-dropdown-link"
                @click="handleProjectDetail(row.projectList)"
              >
                {{ row.projectList[0].projectCode }}
                <el-icon class="el-icon--right"><CaretBottom /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- <el-dropdown-item>
                    <div class="stock-list">
                      <span class="stock-item">关联合同名称</span>
                    </div>
                  </el-dropdown-item> -->
                  <div class="autodropp">
                    <el-dropdown-item
                      v-for="item in row.projectList"
                      :command="item.projectId"
                    >
                      <div class="stock-list">
                        <span class="stock-item">{{ item.projectCode }}</span>
                      </div>
                    </el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <span v-else>--</span>
          </template>
        </el-table-column>

        <el-table-column
          label="项目名称"
          prop="projectName"
          :show-overflow-tooltip="true"
          min-width="150"
        >
          <template #default="{ row }">
            <span>{{ row.projectName ? row.projectName : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="文件编号"
          prop="contractCode"
          :show-overflow-tooltip="true"
          min-width="200"
        >
          <template #default="{ row }">
            <span
              v-if="row.contractCode"
              @click="handlecontractCodeDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.contractCode }}</span
            >
            <span v-else>{{ "--" }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="合作单位"
          prop="partner"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.partner ? row.partner : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="销售金额(元)"
          prop="saleAmount"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.saleAmount ? row.saleAmount : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="采购金额(元)"
          prop="purchaseAmount"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.purchaseAmount ? row.purchaseAmount : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="一期"
          prop="planAmount1"
          :show-overflow-tooltip="true"
          min-width="100"
        >
          <template #default="{ row }">
            <span>{{ row.planAmount1 ? row.planAmount1 : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="二期"
          prop="planAmount2"
          :show-overflow-tooltip="true"
          min-width="100"
        >
          <template #default="{ row }">
            <span>{{ row.planAmount2 ? row.planAmount2 : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="三期"
          prop="planAmount3"
          :show-overflow-tooltip="true"
          min-width="100"
        >
          <template #default="{ row }">
            <span>{{ row.planAmount3 ? row.planAmount3 : "--" }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="四期"
          prop="planAmount4"
          :show-overflow-tooltip="true"
          min-width="100"
        >
          <template #default="{ row }">
            <span>{{ row.planAmount4 ? row.planAmount4 : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="履约保证金(元)"
          prop="refund"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.refund ? row.refund : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="应归档文件"
          prop="shouldCountAll"
          :show-overflow-tooltip="true"
          min-width="100"
        >
          <template #default="{ row }">
            <span>{{ row.shouldCountAll ? row.shouldCountAll : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="实际归档份数"
          prop="realCountAll"
          :show-overflow-tooltip="true"
          min-width="110"
        >
          <template #default="{ row }">
            <span>{{ row.realCountAll ? row.realCountAll : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="签订日期"
          prop="signDate"
          :show-overflow-tooltip="true"
          min-width="100"
        />
        <el-table-column
          label="申请日期"
          prop="applicantDate"
          :show-overflow-tooltip="true"
          min-width="100"
        />
        <el-table-column
          label="经办员"
          prop="userName"
          :show-overflow-tooltip="true"
          min-width="100"
        />
        <el-table-column
          label="档案柜位置"
          prop="space"
          :show-overflow-tooltip="true"
          min-width="100"
        >
          <template #default="{ row }">
            <span>{{ row.space ? row.space : "--" }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import {
  getProjectContractListApi,
  getSynthesisContractListApi,
  getPurContractListApi,
} from "@/api/compact/multiple";
import { getDictsApi } from "@/api/dict";
import useUserStore from "@/store/modules/user";

const router = useRouter();
const activeName = ref("first");
//销售合同列表数据
const projectContractList = ref([]);
//项目采购列表数据
const inoutstockDtlListList = ref([]);
//综合服务合同列表数据
const comprehensiveServicesList = ref([]);

//销售类型列表
const contractList = ref([]);
//所属行业列表
const industryTypeList = ref([]);
//服务项目列表
const serviceTypeList = ref([]);
//筛选时间
let time = ref([]);
// 销售合同列表总数
const total = ref(0);
// 采购合同列表总数
const stockDtltotal = ref(0);
const sumPurchaseAmount = ref(0);
const sumSaleAmount = ref(0);
//综合服务列表总数
const comprehenServicetotal = ref(0);
// 表格加载效果
const loading = ref(false);
//当前用户信息
const userStore = useUserStore();
// 搜索参数
const originalParams = {
  startDate: null, //开始日期
  endDate: null, //结束日期
  contractCode: "", // 合同编号
  partner: "", // 合作单位
  projectCode: "", // 项目编号/项目名称
  type: null, // erp_compact_type1-项目销售,2-项目采购,3-综合服务,4-框架协议,5-运营文件,6-行政文件,7-财务文件
  pageNum: 1,
  pageSize: 50,
};
// 将初始数据转化为响应式对象
const params = reactive({ ...originalParams });

/**
 * @description: 重置
 */
const handleRefresh = () => {
  time.value = [];
  Object.assign(params, {
    startDate: null, //开始日期
    endDate: null, //结束日期
    contractCode: "", // 合同编号
    partner: "", // 合作单位
    projectCode: "", // 项目编号/项目名称
    type: null, // erp_compact_type1-项目销售,2-项目采购,3-综合服务,4-框架协议,5-运营文件,6-行政文件,7-财务文件
    pageNum: 1,
    pageSize: 50,
  });
  if (activeName.value === "first") {
    getList();
  } else if (activeName.value === "second") {
    getstockDtltotalList();
  } else {
    getservicesList();
  }
};
/**
 * @description: 列表查询
 */
const getrealinvent = () => {
  getList();
};
// watch(activeName, (newValue, oldValue) => {
//   // 监听tab变化时将筛选条件数据恢复至原始数据
//   time.value = [];
//   params.startDate = null;
//   params.endDate = null;
//   Object.keys(originalParams).forEach((key) => {
//     params[key] = originalParams[key];
//   });

//   if (newValue === "first") {
//     getList();
//   } else if (newValue === "second") {
//     getstockDtltotalList();
//   } else {
//     getservicesList();
//   }
// });
/**
 * @description: 获取项目销售合同列表
 */
const getList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.startDate = time.value[0];
      params.endDate = time.value[1];
    } else {
      params.startDate = null;
      params.endDate = null;
    }
    const res = await getProjectContractListApi({ pageNum, pageSize }, params);
    projectContractList.value = res.list.rows;
    sumPurchaseAmount.value = res.sumPurchaseAmount;
    sumSaleAmount.value = res.sumSaleAmount;

    console.log(res);
    total.value = res.list.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
/**
 * @description: 获取项目采购列表
 */

const getstockDtltotalList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.startDate = time.value[0];
      params.endDate = time.value[1];
    } else {
      params.startDate = null;
      params.endDate = null;
    }
    params.masterContractType = 2; //列表固定参数
    const res = await getPurContractListApi({ pageNum, pageSize }, params);
    inoutstockDtlListList.value = res.rows;
    stockDtltotal.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
/**
 * @description: 获取综合服务合同列表
 */

const getservicesList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.startDate = time.value[0];
      params.endDate = time.value[1];
    } else {
      params.startDate = null;
      params.endDate = null;
    }
    const res = await getSynthesisContractListApi(
      { pageNum, pageSize },
      params
    );
    comprehensiveServicesList.value = res.rows;
    comprehenServicetotal.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 处理导出
 * @param {String} flag 1.列表 2.明细列表
 */
const handleExport = async () => {
  console.log("daochu", activeName.value);
  // 日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  let month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，因此要加1
  if (month < 10) {
    month = "0" + month;
  }
  const day = currentDate.getDate();
  let date = year + "" + month + "" + day;
  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100);
  // 用户昵称
  let userName = userStore.name;
  // 文件名
  let fileNmae = date + userName + randomNum;
  let { pageNum, pageSize } = params;
    /* 导出列表 */
    proxy.download(
      `/system/compact/exportAllContractList?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `${fileNmae}.xlsx`,
      null,
      1
    );
  
};
function formatContractMoney(row, column, cellValue) {
  // 判断数据是否为数字
  if (typeof cellValue === "number" && !isNaN(cellValue)) {
    // 将数据保留两位小数
    const formattedValue = cellValue.toFixed(2);
    return formattedValue;
  } else {
    // 如果数据不是数字，则原样返回
    return cellValue;
  }
}
/* 跳转营销合同详情 */
const handlecontractCodeDetail = (row) => {
  let url = "";
  let info = {}
  console.log("跳转合同详情");
  console.log(row);
  switch (row.type) {
    // 销售合同
    case "1":
      url = `/SealManage/contract`;
      console.log(url)
      info = { contractId: row.contractId }
      break;
    // 项目采购
    case "2":
      url = `/SealManage/contractSeal`;
      info = { purchaseContractId: row.contractId }
      break;
    //综合服务
    case "3":
      url = `/SealManage/serveContract`;
      info = { contractId: row.contractId }
      break;
    // 框架协议
    case "4":
      url = `/SealManage/contractFrame`;
      info = { contractId: row.contractId }
      break;

    default:
      url = `/SealManage/circulation`;
      info = { contractId: row.contractId }
      break;
     
  }
      const { href } = router.resolve({
        path: url,
        query:info ,
      });
      window.open(href, "_blank");
};
/* 跳转采购合同详情 */
const handlePurchaseDetail = (row) => {
  const { href } = router.resolve({
    path: `/SealManage/contractSeal`,
    query: { purchaseContractId: row.purchaseContractId },
  });
  window.open(href, "_blank");
};
/* 跳转销售合同/采购合同详情 */
const handleContractDetail = (row) => {
  if (row.modelTypeName === "综合服务模块") {
    const { href } = router.resolve({
      path: `/SealManage/serveContract`,
      query: { contractId: row.synthesisContractId },
    });
    window.open(href, "_blank");
  } else {
    const { href } = router.resolve({
      path: `/SealManage/contractSeal`,
      query: { purchaseContractId: row.synthesisContractId },
    });
    window.open(href, "_blank");
  }
};
/* 点击行内库存数据 */
const handleStock = async (command) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: command },
  });
  window.open(href, "_blank");
};
/* 跳转项目详情 */
const handleProjectDetail = (row) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: row[0].projectId },
  });
  window.open(href, "_blank");
};

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 销售类型
  await getDictsApi("erp_compact_type").then((res) => {
    if (res.code === 200) {
      // contractList.value = res.data;
      contractList.value = res.data.reduce(
        function (acc, obj) {
          if (
            ["项目销售", "项目采购", "综合服务", "框架协议"].includes(obj.label)
          ) {
            acc[0].options.push(obj);
          } else {
            acc[1].options.push(obj);
          }
          return acc;
        },
        [
          { label: "合同类", options: [] },
          { label: "非合同类", options: [] },
        ]
      );
    }
  });

  // 所属行业
  await getDictsApi("erp_purchase_detail_type").then((res) => {
    if (res.code === 200) {
      industryTypeList.value = res.data.filter(
        (item) => item.value === 0 || item.value === 1
      );
    }
  });
  // 服务项目
  await getDictsApi("erp_export_detail_type").then((res) => {
    if (res.code === 200) {
      serviceTypeList.value = res.data;
    }
  });
}
onMounted(() => {
  getDicts();
  getList();
});
</script>

<style lang="scss" scoped>
.requestAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .sum-box {
    height: 56px;
    display: flex;
    margin-bottom: 20px;
    .sum-box-item {
      width: 420px;
      height: 100%;
      background-color: #f8faff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
    }
    .sum-text {
      color: #409eff;
      line-height: 200px;
    }
  }
  .pagination {
    margin-top: 20px;
  }
  :deep(.el-tabs__item.is-top) {
    width: 120px;

    font-size: 16px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}
</style>
